<template>
  <fks-row class="flow-button-warp">
    <slot name="before"></slot>
    <template v-if="type !== 'view'">
      <fks-button
        v-for="(item, index) in buttonList"
        :key="index"
        :plain="item.type !== 'submit'"
        :type="buttonType(item)"
        :loading="loading"
        @click="clickHandler(item)"
      >
        <i
          v-if="!loading"
          style="margin-right: 6px; vertical-align: middle"
          :class="`fks-icon-${buttonIcon(item)}`"
        />

        <span style="display: inline-block; vertical-align: middle">{{
          LANG[item.customCode || item.code] || item.text
        }}</span>
      </fks-button>
    </template>
    <template v-if="type === 'view'">
      <fks-button type="primary" :loading="loading" @click="getPdf"
        >打印表单</fks-button
      >
    </template>
    <slot name="after"></slot>
    <fks-dialog
      title="选择加签人"
      append-to-body
      :visible.sync="addCounterInfo.visible"
      width="400px"
    >
      <fks-form>
        <fks-form-item label="选择委托人">
          <fks-user-selector
            style="width: 100%"
            url
            multiple
            :username.sync="addCounterInfo.userName"
            :userfullname.sync="addCounterInfo.userFullName"
          ></fks-user-selector>
        </fks-form-item>
      </fks-form>
      <span slot="footer" class="dialog-footer">
        <fks-button @click="addCounterInfo.visible = false">取 消</fks-button>
        <fks-button type="primary" @click="addCounterHandler">确 定</fks-button>
      </span>
    </fks-dialog>
    <fks-dialog
      title="选择退回节点"
      :visible.sync="innerRejectVisible"
      @close="cancelReject()"
      append-to-body
    >
      <fks-select v-model="rejectNode" placeholder="请选择退回节点">
        <fks-option
          v-for="item in rejectNodeOptions"
          :key="item.taskKey"
          :label="item.taskName"
          :value="item.taskKey"
        >
        </fks-option>
      </fks-select>
      <div slot="footer" class="dialog-footer">
        <fks-button @click="cancelReject()">取 消</fks-button>
        <fks-button type="primary" @click="confirmReject()">确 定</fks-button>
      </div>
    </fks-dialog>
    <fks-dialog
      title="选择抄送人"
      @open="open"
      append-to-body
      :visible.sync="circulationInfo.visible"
      @close="cancel()"
      width="400px"
    >
      <fks-form>
        <fks-form-item label="抄送人">
          <fks-user-selector
            style="width: 100%"
            url
            multiple
            :username.sync="circulationInfo.userName"
            :userfullname.sync="circulationInfo.userFullName"
          ></fks-user-selector>
        </fks-form-item>
        <fks-form-item label="抄送人通知方式">
          <fks-checkbox-group
            v-model="notifyMethods"
            @change="handleNotifyMethodsChange"
          >
            <fks-checkbox
              v-for="item in notifyMethodOptions"
              :label="item.value"
              :key="item.value"
              >{{ item.label }}
            </fks-checkbox>
          </fks-checkbox-group>
        </fks-form-item>
      </fks-form>
      <span slot="footer" class="dialog-footer">
        <fks-button @click="cancel">取 消</fks-button>
        <fks-button type="primary" @click="circulationInfoHandler"
          >确 定</fks-button
        >
      </span>
    </fks-dialog>
  </fks-row>
</template>
<script>
import Mix from '@/mixins/module'
import {
  processMulti,
  processReject,
  processButton,
  circulation,
  processTaskKey
} from './api'

export default {
  name: 'FlowButton',
  mixins: [Mix],
  props: {
    loading: false,
    taskKey: '',
    comment: '',
    approval: '',
    userNameList: {
      type: Array,
      default: () => {
        return []
      }
    },
    formName: '',
    modelKey: ''
  },
  data() {
    return {
      type: this.$route.params.type,
      bizId: this.$route.params.bizId,
      formKey: this.$route.params.formKey,
      taskId: this.$route.params.taskId,
      flowData: {
        modelKey: this.modelKey,
        bizId: this.$route.params.bizId,
        processInstanceId:
          this.$route.params.processInstanceId ||
          this.$route.query.processInstanceId ||
          '', // 流程实例ID
        formKey: this.formKey,
        taskId: this.$route.params.taskId,
        approval: this.approval,
        comment: this.comment
      },
      addCounterInfo: {
        visible: false, // 选择退回节点对话框
        userName: '',
        userFullName: '',
        targetNode: ''
        // flowIndex: '',
        // flowDetail: []
      },
      buttonList: [],
      //退回
      rejectNodeOptions: [],
      innerRejectVisible: false,
      rejectNode: '',
      //抄送
      circulationInfo: {
        visible: false, // 选择退回节点对话框
        userName: '',
        userFullName: '',
        notify: ''
      },
      notifyMethods: [],
      notifyMethodOptions: [
        {
          label: '站内信',
          value: '0'
        },
        {
          label: '短信',
          value: '1'
        },
        {
          label: '邮件',
          value: '2'
        }
      ]
    }
  },
  watch: {
    modelKey(val) {
      this.flowData.modelKey = val
    }
  },
  methods: {
    buttonType(item) {
      switch (item.type) {
        case 'submit':
          return 'primary'
        default:
          return ''
      }
    },
    buttonIcon(item) {
      switch (item.type) {
        case 'abandon':
          return 'delete'
        case 'reject':
          return 'reject'
        case 'submit':
          return 'check'
        case 'saveDraft':
          return 'hold'
        case 'addCountersignee':
          return 'circle-plus-outline'
        case 'edit':
          return 'edit'
        case 'circulate':
          return 'message-pass'
        default:
          return ''
      }
    },
    sortIcon(item) {
      switch (item.type) {
        case 'submit':
          return 1
        case 'saveDraft':
          return 2
        case 'reject':
          return 3
        case 'abandon':
          return 4
        case 'addCountersignee':
          return 5
        case 'edit':
          return 6
        case 'circulate':
          return 7
        default:
          return 8
      }
    },
    /**
     * @description: 按钮点击事件
     * @param {type} 按钮触发的方法类型
     */
    clickHandler(buttonInfo) {
      if (buttonInfo.type == 'reject') {
        //只有一个退回节点直接退回并return
        if (buttonInfo.targetNode.length === 1) {
          buttonInfo.targetNode = buttonInfo.targetNode[0]
          this.reject(buttonInfo)
          return
        }
        //有多个节点可选打开弹窗
        processTaskKey(this.taskId).then((res) => {
          if (res.status) {
            let nodeArr = res.data
            let rejectNodeArr =
              Object.prototype.toString.call(buttonInfo.targetNode) ==
              '[object Array]'
                ? buttonInfo.targetNode
                : JSON.parse(buttonInfo.targetNode)
            for (const item of nodeArr) {
              if (rejectNodeArr.indexOf(item.taskKey) !== -1) {
                this.rejectNodeOptions.push(item)
              }
            }
          }
        })
        this.innerRejectVisible = true
      } else {
        this[buttonInfo.type](buttonInfo)
      }
    },
    /**
     * @description: 完成操作成功之后的回调
     */
    getButton() {
      if (this.taskId) {
        processButton(this.taskId).then((res) => {
          const tempButtonList = JSON.parse(res.data.buttonList)
          if (
            tempButtonList.taskButtonList &&
            tempButtonList.taskButtonList.length
          ) {
            this.buttonList = tempButtonList.taskButtonList.sort(
              (a, b) => this.sortIcon(b) - this.sortIcon(a)
            )
          } else {
            this.buttonList = tempButtonList.sort(
              (a, b) => this.sortIcon(b) - this.sortIcon(a)
            )
          }
        })
      }
    },
    /**
     * @description: 提交请求
     */
    submit(buttonInfo) {
      this.$emit('submit', buttonInfo)
    },
    /**
     * @description: 暂存
     */
    async saveDraft(buttonInfo) {
      this.$emit('preSave', buttonInfo)
    },
    /**
     * @description: 废弃
     */
    abandon(buttonInfo) {
      this.$emit('abandon', buttonInfo)
    },
    //取消退回
    cancelReject() {
      this.rejectNode = ''
      this.innerRejectVisible = false
      this.rejectNodeOptions = []
      this.$emit('update:loading', false)
    },
    //确认退回
    confirmReject() {
      let rejectIndex = this.buttonList.findIndex(
        (item) => item.type == 'reject'
      )
      if (rejectIndex > -1) {
        let buttonInfo = this.buttonList[rejectIndex]
        buttonInfo.targetNode = this.rejectNode
        this.reject(buttonInfo)
      }
      this.$emit('update:loading', false)
    },
    /**
     * @description: 驳回到指定节点
     * @param {taskId} 任务id
     * @param {comment} 评论
     * @param {targetKey} 指定节点
     */
    reject(buttonInfo) {
      const flowData = {
        taskId: this.flowData.taskId,
        bizId: this.flowData.bizId,
        comment: this.flowData.comment,
        targetKey: buttonInfo.targetNode || buttonInfo.rejectNode,
        isSubToPre: buttonInfo.rejectType === 2
      }
      processReject(flowData)
        .then((res) => {
          if (res.status) {
            this.onOptSuccess(res, 'REJECT')
          }
        })
        .catch((err) => {
          this.catchHandler(err)
        })
      this.$emit('update:loading', false)
    },
    /**
     * @description: 抄送
     */
    open() {
      this.circulationInfo.userName = ''
      this.circulationInfo.userFullName = ''
      this.notifyMethods = []
    },
    cancel() {
      this.circulationInfo.visible = false
      this.$emit('update:loading', false)
    },
    circulate(buttonInfo) {
      console.log(buttonInfo)
      this.circulationInfo.visible = true
    },
    circulationInfoHandler() {
      if (
        this.circulationInfo.userName &&
        this.circulationInfo.userName.length
      ) {
        circulation({
          formBizId: this.flowData.bizId,
          formKey: this.flowData.formKey,
          processInstanceId: this.flowData.processInstanceId,
          processType: this.isCustom ? 2 : 1,
          receiverUserName: this.circulationInfo.userName,
          receiverUserFullName: this.circulationInfo.userFullName,
          notify: this.circulationInfo.notify,
          senderUserFullName: this.$store.state.user.userFullname,
          senderUserName: this.$store.state.user.userName,
          taskId: this.flowData.taskId,
          title: this.formName || '',
          sourceId: this.$store.state.portal.id || '',
          sourceName: this.$store.state.portal.name || ''
        }).then((res) => {
          this.receiverUserName = ''
          this.$message({
            type: 'success',
            message: '抄送成功',
            showClose: true
          })
          this.circulationInfo.visible = false
          this.$emit('update:loading', false)
        })
      } else {
        this.$message({
          type: 'error',
          message: '无抄送人',
          showClose: true
        })
      }
    },
    handleNotifyMethodsChange(val) {
      if (val && val.length && val.length > 0) {
        this.circulationInfo.notify = val.join()
      } else {
        this.circulationInfo.notify = ''
      }
    },
    /**
     * @description: 加签
     */
    addCountersignee(buttonInfo) {
      this.addCounterInfo.targetNode = buttonInfo.targetNode
      this.addCounterInfo.visible = true
    },
    addCounterHandler() {
      // 选择完加签人后进行流程提交
      if (this.addCounterInfo.targetNode && this.addCounterInfo.userName) {
        processMulti(
          'add',
          this.taskId,
          this.addCounterInfo.targetNode,
          this.addCounterInfo.userName
        ).then((res) => {
          this.addCounterInfo.targetNode = ''
          this.addCounterInfo.userName = ''
          this.addCounterInfo.userFullName = ''
          this.addCounterInfo.visible = false
          this.onOptSuccess(res, 'ADDCOUNTER')
        })
      } else {
        if (this.addCounterInfo.userName) {
          this.addCounterInfo.visible = false
          this.onOptSuccess({
            status: false,
            message: 'No assignee or node'
          })
        } else {
          this.$message({
            type: 'warning',
            message: 'No assignee',
            showClose: true
          })
        }
      }
    },
    /**
     * @description: 减签
     */
    deleteCountersignee() {
      processMulti('delete', this.taskId, this.taskKey, this.userNameList).then(
        (res) => {
          this.onOptSuccess(res, 'DELETECONTER')
        }
      )
    },
    /**
     * @description: 打开选择退回节点dialog
     */
    stepClickHandler(stepId) {
      this.flowIndex = this.flowIndex == stepId ? '' : stepId
    },
    onOptSuccess(data, type) {
      if (data.status) {
        this.$emit('onSuccess', data, type)
      } else {
        this.$emit('onError', data, type)
      }
      this.$emit('update:loading', false)
    },
    /**
     * @description:
     * @param {type}
     * @return:
     */
    catchHandler(error) {
      this.$emit('update:loading', false)
      throw new Error(error)
      // this.$emit('onCatch', error)
    },
    /**
     * @description:导出pdf
     */
    getPdf() {
      this.$emit('getPdf')
    }
  },
  mounted() {
    if (this.taskId && this.type === 'execute') {
      this.getButton()
    } else if (this.type && this.type === 'add') {
      this.buttonList = [
        {
          type: 'saveDraft',
          text: '暂存',
          code: 'SAVEDRAFT',
          customCode: 'SAVEDRAFT'
        },
        {
          type: 'submit',
          text: '提交',
          code: 'SUBMIT',
          customCode: 'SUBMIT'
        }
      ]
    } else if (this.type && this.type === 'edit') {
      this.buttonList = [
        {
          type: 'submit',
          text: '修改',
          code: 'EDIT',
          customCode: 'SUBMIT'
        }
      ]
    }
  }
}
</script>
<style lang="scss" scoped>
.flow-button-warp {
  ::v-deep .flow-button-inner {
    display: inline-block;
    align-items: center;
  }

  .fks-steps {
    .fks-step {
      cursor: pointer;
    }

    .fks-step.active {
      .fks-step__main {
        color: #4ccae3 !important;
      }

      .fks-step__title {
        color: #4ccae3 !important;
      }

      .fks-step__description {
        color: #4ccae3 !important;
      }

      .fks-step__icon {
        color: #4ccae3 !important;
        border-color: #4ccae3 !important;
      }
    }
  }
}
</style>
